import { filterNonNullable } from '@/library/util/array';
// import frontDynamicRoutes from '@/router/dynamic-routes-front';
import { getRoutePrefix } from '@/router/helpers';
import { MenuItem } from '@/router/menu';
// import { NavResponse, SubSystemResponse } from '@/services/auth';
import { RouteRecordRaw } from 'vue-router';

/**
 * 从 nav 中获取权限列表
 * @param nav
 * @returns
 */
function getAuthsFromNav(nav: any): string[] {
  const paths: string[] = [];

  if (nav.path) {
    paths.push(nav.path);
  }

  if (nav.children) {
    nav.children.forEach((child) => {
      paths.push(...getAuthsFromNav(child));
    });
  }

  return paths;
}

/**
 * 从 subsystem 中获取权限列表
 * @param subSystem
 * @returns
 */
export function getAuthsFromSubSystem(
  // subSystem: SubSystemResponse | undefined,
  subSystem: any,
): Set<string> {
  const navs = subSystem?.nav ?? [];

  const auths = navs.flatMap(getAuthsFromNav);

  return new Set(auths);
}

/**
 * 从路由获取菜单
 * @param route
 * @param auths
 * @param prePath
 * @returns
 */
function getMenuFromRoute(
  route: RouteRecordRaw,
  auths: Set<string>,
  prePath = '',
): MenuItem | undefined {
  const menuConf = route.meta?.menu;
  if (typeof menuConf !== 'string') {
    return undefined;
  }

  const fullPath = route.path.startsWith('/')
    ? route.path
    : prePath + '/' + route.path;

  let authPath: string | undefined;
  const authConf = route.meta?.auth;
  if (typeof authConf === 'string') {
    authPath = authConf;
  } else if (authConf === true) {
    authPath = fullPath;
  }

  if (authPath && !auths.has(authPath)) {
    return undefined;
  }

  const icon = route.meta?.icon as any;
  const menuItem: MenuItem = {
    icon: icon || '',
    title: menuConf,
    path: fullPath,
  };

  // 子级
  const childrenWithMenu = (route.children ?? []).filter((child) => {
    return !!child.meta?.menu;
  });
  if (childrenWithMenu && childrenWithMenu.length) {
    const filteredChildren = childrenWithMenu
      .map((child) => getMenuFromRoute(child, auths, fullPath))
      .filter(filterNonNullable);

    // 子级全被过滤掉则父级也不显示
    if (filteredChildren.length === 0) {
      return undefined;
    }

    menuItem.children = filteredChildren;
  }

  return menuItem;
}

/**
 * 从路由和权限获取菜单
 * @param routes
 */
export const getMenusFromRoutes = (
  routes: RouteRecordRaw[],
  auths: Set<string>,
  type: 'front' | 'back',
): MenuItem[] => {
  const results = routes
    .filter((route) => {
      // 只获取顶层
      const prefix = getRoutePrefix(route.path, 1);
      if (prefix !== route.path) {
        return false;
      }

      // 有菜单的
      if (!route.meta?.menu) {
        return false;
      }

      // 前台路由/后台路由
      const isBackEnd = prefix.startsWith('/system');
      return type === 'back' ? isBackEnd : !isBackEnd;
    })
    .sort(
      (route1, route2) =>
        ((route1.meta?.index as number | undefined) ?? 0) -
        ((route2.meta?.index as number | undefined) ?? 0),
    )
    .map((route) => getMenuFromRoute(route, auths))
    .filter(filterNonNullable);

  return results;
};
